package com.openflag.bwicservice.service.impl;

import com.openflag.bwicservice.domain.Bid;
import com.openflag.bwicservice.repository.BidRepository;
import com.openflag.bwicservice.service.AuditService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AuditServiceImpl implements AuditService {
    private Logger LOG = LoggerFactory.getLogger(AuditServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private BidRepository bidRepository;

    @Override
    public Integer getCount(Long bwicId) {
        try {
            List<Bid> list = bidRepository.getBidList(bwicId);
//            Integer count = restTemplate.getForObject("http://localhost:8000/count/{id}", Integer.class, bwicId);

            Integer count = list.size();

            return count;
        } catch (Exception e) {
            LOG.error("Error when get count from audit service: {}", e.getMessage());
        }
        return null;
    }

    @Override
    public String getMyRank(Long bwicId, Long clientId) {
        try {
            List<Bid> bidList = bidRepository.getBidList(bwicId);
//            String myRank = restTemplate.getForObject("http://localhost:8000/myrank/{bwicId}/{clientId}", String.class, bwicId, clientId);
            List<Bid> sortedList = bidList.stream()
                    .sorted(Comparator.comparingLong(Bid::getBidMarketValue).reversed())
                    .collect(Collectors.toList());

            Bid queryBid = bidRepository.getBidByBwicIdAndClientId(bwicId,clientId);

            Integer myRank = sortedList.indexOf(queryBid);
            myRank++;

            return myRank.toString();
        } catch (Exception e) {
            LOG.error("Error when get rank from audit service: {}", e.getMessage());
        }
        return null;
    }
}
